
import { API } from "../../utils/api"
import React, { Component } from 'react'
import { Link } from 'react-router-dom'
import TitBar from "../../components/TitBar"
import { Toast } from 'antd-mobile';
import "./index.scss"
import { BASE_URL } from "../../utils/url";
import HouseItem from "../../components/HouseItem";
const BMapGL = window.BMapGL

const labelStyles = {
    cursor: 'pointer',
    border: '0px solid rgb(225,0,0)',
    padding: '0px',
    whiteSpace: 'nowrap',
    fontSize: '12px',
    color: 'rgb(225,225,225)',
    textAlign: 'center'

}
export default class Map extends Component {
    state = {
        housesList: [],
        isShow: false
    }
    componentDidMount() {
        this.initMap()
    }
    // 初始化地图
    initMap() {
        // 获取到localStorage中当前城市信息
        const { label, value } = JSON.parse(localStorage.getItem('hkzf_city'))

        const map = new BMapGL.Map("container");
        // 利用百度地图地址解析API使当前城市显示在屏幕正中间
        this.map = map
        const myGeo = new BMapGL.Geocoder();
        myGeo.getPoint(label, async (point) => {
            if (point) {
                // 初始化地图
                map.centerAndZoom(point, 11);
                // 地图标注
                // map.addOverlay(new BMapGL.Marker(point));
                //添加常用控件
                map.addControl(new BMapGL.ScaleControl());
                map.addControl(new BMapGL.ZoomControl());
                // 调用  renderOverlays() 方法      
                this.renderOverlays(value)
            }
        }, label)
        // 地图移动事件
        map.addEventListener('movestart', () => {
            if (this.state.isShow === true)
                this.setState({ isShow: false })
        })
    }
    // 渲染覆盖入口
    async renderOverlays(id) {
        Toast.loading('加载中...', 0, null, false)
        const res = await API.get(`/area/map?id=${id}`)
        // console.log('renderOverlays函数获取的数据:', res)
        const data = res.data.body
        //调用getTypeAndZoom() 方法
        const { nextZoom, type } = this.getTypeAndZoom()
        data.forEach(item => {
            // 创建覆盖物
            this.createOverlays(item, nextZoom, type)
        });
        Toast.hide()
    }
    //计算覆盖物的类型和缩放级别
    getTypeAndZoom() {
        const zoom = this.map.getZoom()
        let nextZoom, type
        // console.log(zoom)
        if (zoom >= 10 && zoom < 12) {
            //区
            //下一个缩放级别
            nextZoom = 13
            type = 'circle'
        } else if (zoom >= 12 && zoom < 14) {
            //镇
            //下一个缩放级别
            nextZoom = 15
            type = 'circle'
        } else if (zoom >= 14 && zoom < 16) {
            //小区
            //下一个缩放级别
            type = 'rect'
        }
        return { nextZoom, type }
    }

    createOverlays(data, zoom, type) {
        const {
            coord: { longitude, latitude },
            label: areaName,
            count,
            value
        } = data
        const areapoint = new BMapGL.Point(longitude, latitude)
        if (type === 'circle') {
            // 创建区或者镇
            this.createCircle(areapoint, areaName, count, value, zoom)
        } else {
            //创建小区
            this.createRect(areapoint, areaName, count, value)
        }
    }
    // 创建区和镇
    createCircle(point, name, count, id, zoom) {
        // 添加文本覆盖物
        // 1创建Label实例对象 2调用setStyle()方法设置样式 3在map对象上调用addOverlay方法将覆盖物加入到地图中
        const label = new BMapGL.Label('', {
            position: point,
            offset: new BMapGL.Size(-30, -30)
        })
        //设置每个label唯一值
        label.id = id
        //设置房源覆盖物
        label.setContent(`
                    <div class="bubble">
                        <p class="bubble-name">${name}</p>
                        <p class="bubble-count">${count}套</p>
                    </div>
                `)
        //设置样式
        label.setStyle(labelStyles)
        //添加点击事件
        label.addEventListener('click', () => {
            //获取该区域下的房源数据
            this.renderOverlays(id)
            //以点击的覆盖物位中心放大地图
            this.map.centerAndZoom(point, zoom);
            //清除覆盖物 重新获取下一级覆盖物
            this.map.clearOverlays()

        })
        //添加覆盖物到地图中
        this.map.addOverlay(label)

    }

    // 创建小区
    createRect(point, name, count, id) {
        const label = new BMapGL.Label('', {
            position: point,
            offset: new BMapGL.Size(-50, -24)
        })
        //设置每个label唯一值
        label.id = id
        //设置房源覆盖物
        label.setContent(`
                    <div class="rect">
                        <p class="rect-name">${name}</p>
                        <p class="rect-count">${count}套</p>
                    </div>
                `)
        //设置样式
        label.setStyle(labelStyles)
        //添加点击事件
        label.addEventListener('click', (e) => {
            // 获取当前点击项
            // console.log(e.domEvent)
            const target = e.domEvent.changedTouches[0]
            this.map.panBy(
                window.innerWidth / 2 - target.clientX,
                (window.innerHeight - 235) / 2 - target.clientY
            )
            this.getHousesList(id)
            this.setState({ isShow: true })
        })
        //添加覆盖物到地图中
        this.map.addOverlay(label)
    }
    // 获取小区房屋列表数据
    async getHousesList(id) {
        Toast.loading('加载中...', 0, null, false)
        const res = await API.get(`/houses?cityId=${id}`)
        this.setState({ housesList: res.data.body.list })
        // console.log(this.state.housesList)
        Toast.hide()
    }
    // 渲染小区房屋信息
    renderHousesList = () => {
        return this.state.housesList.map(item => (
            <HouseItem
                key={item.houseCode}
                src={BASE_URL + item.houseImg}
                title={item.title}
                desc={item.desc}
                tags={item.tags}
                price={item.price}
            />
        ))
    }
    render() {

        return (
            <div className="map">
                <TitBar title='地图找房'></TitBar>
                {/* 地图 */}
                <div id="container"></div>
                {/* 房源信息 */}
                {this.state.isShow === true ? <div className="house-list">
                    {/* 标题 */}
                    <div className="house-list-title">
                        <p className="house-list-title-left">房源信息</p>
                        <Link className="house-list-title-more" to='/home/searchhouse'>更多房源</Link>
                    </div>
                    {/* 列表 */}
                    <div className="house-list-contaner">
                        {this.renderHousesList()}
                    </div>
                </div> : ''}

            </div>
        )
    }
}
